package com.jf.cloud.service.sysmanager.remote.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.util.DateUtil;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.TokenUtil;
import com.jf.cloud.service.sysmanager.constant.UserConstant;
import com.jf.cloud.service.sysmanager.constant.sms.SmsConstant;
import com.jf.cloud.service.sysmanager.dao.IPubgOperateLogService;
import com.jf.cloud.service.sysmanager.dao.IPubgUserService;
import com.jf.cloud.service.sysmanager.dao.ISmsService;
import com.jf.cloud.service.sysmanager.entity.PubgUser;
import com.jf.cloud.service.sysmanager.entity.SysStaff;
import com.jf.cloud.service.sysmanager.handler.TokenHandler;
import com.jf.cloud.service.sysmanager.support.entity.Result;
import com.jf.cloud.service.sysmanager.support.web.BaseController;

@Controller
@RequestMapping("/appLogin")
public class AppLoginController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(AppLoginController.class);

	@Resource
	private IPubgUserService pubgUserService;
	
	@Resource
	private TokenHandler tokenHandler;
	
	/**
	 * 短信相关服务
	 */
	@Resource
	private ISmsService smsService;
	
	@Resource
	private IPubgOperateLogService pubgOperateLogService;
	
	/**
	 * 前台短信登陆
	 * 
	 * @author 朱建文 创建时间：2018年3月31日 下午4:20:40
	 */
	@ResponseBody
	@RequestMapping("/smsLogin")
	public Result<Map<String, Object>> smsLogin(HttpServletRequest request, HttpServletResponse response) {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		result.setCode(-1);
		result.setMessage("登陆失败");
		try {
			
			String userAccount = getParamValueString(request, "userName");
			String mobileCaptcha = getParamValueString(request, "mobileCaptcha", ""); // 手机验证码
			
			// 手机短信验证码验证
			String rs = "";
			try {
				rs = smsService.checkSMS(null, userAccount, SmsConstant.USER_PHONE_MODEL_TYPE_100, mobileCaptcha);
			} catch (Exception e) {
				log.error("手机注册短信验证码有误", e);
			}
//			if (!"0".equals(rs)) {
//				log.error("手机验证码错误：" + rs);
//				result.setMessage(rs);
//				return result; // 手机验证码错误
//			}
			
			// 查询是否新用户
			Query query = new Query();
			query.put("USER_ACCOUNT", userAccount);
			List<PubgUser> pubgUserList = pubgUserService.findList(query);
			if (pubgUserList != null && pubgUserList.size() > 1) {
				result.setMessage("帐号存在多个，请联系管理员");
				return result;
			}
			
			PubgUser pubgUser = null;
			if (pubgUserList == null || pubgUserList.isEmpty()) {
				log.info("新账号登录！");
				Integer regFrom = getParamValueInteger(request, "regFrom", 10);
				String regIp = getParamValueString(request, "regIp");
				pubgUser = new PubgUser();
				pubgUser.setUserAccount(userAccount);
				pubgUser.setUserRole(UserConstant.USER_ROLE_10.getId());
				pubgUser.setRegFrom(regFrom);
				pubgUser.setRegIp(regIp);
				pubgUser.setRegTime(DateUtil.getCurrentDateTime());
				pubgUser.setInfoCompleteFlag(0);
				pubgUser.setBalance(0.0);
				pubgUser.setMatchAmount(0);
				pubgUser.setWinAmount(0);
				pubgUser.setWinSum(0.0);
				pubgUser = pubgUserService.saveObj(pubgUser);
				
				// 插入注册记录
				pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_10.getId().longValue(), UserConstant.USER_OPT_TYPE_10.getName());
			}
			
			if (pubgUser == null) {
				pubgUser = pubgUserList.get(0);
			}
			
			// 插入登陆记录
			pubgOperateLogService.insertUserOperateLog(pubgUser.getRowId(), UserConstant.USER_OPT_TYPE_20.getId().longValue(), UserConstant.USER_OPT_TYPE_20.getName());
			
			// 把登录成功后token保存
			String token = TokenUtil.buildToken();
			tokenHandler.putToken(token, pubgUser.getRowId() + "", pubgUser.getRowId() + "");
			pubgUser.setToken(token);
			
			// 更新验证码状态
			smsService.updateUserPhoneYzmState(null, userAccount, SmsConstant.USER_PHONE_MODEL_TYPE_100);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("token", token);
			data.put("rowId", pubgUser.getRowId());
			data.put("userAccount", pubgUser.getUserAccount().substring(0, 3) + "****" + pubgUser.getUserAccount().substring(8));
			data.put("nickname", pubgUser.getNickname() == null ? "" : pubgUser.getNickname());
			data.put("nicknameInitial", pubgUser.getNicknameInitial() == null ? "" : pubgUser.getNicknameInitial());
			data.put("gameRole", pubgUser.getGameRole() == null ? "" : pubgUser.getGameRole());
			data.put("linkQq", pubgUser.getLinkQq() == null ? "" : pubgUser.getLinkQq());
			data.put("balance", pubgUser.getBalance() == null ? 0 : pubgUser.getBalance());
			data.put("photo", pubgUser.getPhoto() == null ? "" : pubgUser.getPhoto());
			data.put("userRole", pubgUser.getUserRole());
			data.put("infoCompleteFlag", pubgUser.getInfoCompleteFlag() == null ? 0 : pubgUser.getInfoCompleteFlag());
			
			result.setCode(0);
			result.setData(data);
			result.setMessage("登陆成功");
		} catch (Exception e) {
			log.error("***************用户登录出错了", e);
		}
		return result;
	}

	/**
	 * 退出
	 * 
	 * @author 朱建文 创建时间：2017年12月20日 下午1:51:23
	 */
	@ResponseBody
	@RequestMapping("/recLogout")
	public String logout(String token, HttpServletRequest request){
		Result<SysStaff> result = new Result<SysStaff>();
		result.setCode(-1);
		result.setMessage("退出登录出错了");
		try {
			SysStaff user = (SysStaff) request.getSession().getAttribute("user");
			tokenHandler.removeSysToken(token, JsonUtil.toJSON(user));
			result.setCode(0);
		} catch (Exception e) {
			log.error("退出出错", e);
		}
		return result.toString();
	}
}
